<template>
  <van-swipe-cell v-for="blog in props.blogList || []" :key="blog.id">
    <van-card
        :desc="blog.content"
        :title="blog.title"
        class="blog-card"
        :thumb="processImageUrl(blog.coverImage)"
        @click="toBlog(blog.id)">
      <template #tags>
        <van-tag
            plain
            color="#ffe1e1"
            text-color="#ad0000"
            style="margin-right: 8px;"
            v-for="(tag, index) in getBlogTags(blog)"
            :key="index">
          {{ tag }}
        </van-tag>
      </template>
    </van-card>
    <template #right v-if="blog.blogUserVO && currentUser && blog.blogUserVO.id === currentUser.id">
      <van-button round text="删除" type="danger" class="button" @click="deleteBlog(blog.id)"
                  v-if="blog.blogUserVO.id === currentUser.id"/>
      <van-button round text="修改" type="success" class="button" @click="toEditBlog(blog.id)"
                  v-if="blog.blogUserVO.id === currentUser.id"/>
    </template>
    <template #right v-else-if="blog.blogUserVO && currentUser && blog.blogUserVO.id !== currentUser.id">
      <van-button round text="点赞" type="success" class="button" @click="likeBlog(blog.id, blog.isLiked || false)"/>
      <van-button round text="收藏" type="success" class="button" @click="starBlog(blog.id, blog.isStarred || false)"/>
    </template>
  </van-swipe-cell>

</template>

<script setup lang="ts">
// import {BlogType} from "../models/blog";
import {useRouter} from "vue-router";
import {onMounted, ref, defineEmits, defineProps} from "vue";
import {getCurrentUser} from "../services/user";
import myAxios from "../plugins/myAxios";
import {showToast} from "vant";
import { processImageUrl } from '../utils/imageUtils';

// 定义Blog接口
interface BlogUserVO {
  id: number;
  username?: string;
  avatarUrl?: string;
}

interface Blog {
  id: number;
  title: string;
  content: string;
  coverImage?: string;
  tags?: string;
  blogUserVO?: BlogUserVO;
  isLiked?: boolean;
  isStarred?: boolean;
}

const router = useRouter();

const currentUser = ref();

const emit = defineEmits(['delete-blog']);

const props = defineProps({
  blogList: {
    type: Array as () => Blog[],
    required: true
  }
});

onMounted(async () => {
  currentUser.value = await getCurrentUser();
  console.log(currentUser.value?.id);
});

const deleteBlog = async (id: number) => {
  const res: any = await myAxios.post('/blog/delete', {
    id: id,
  });
  if (res?.code === 0) {
    showToast('删除成功');
    emit('delete-blog');
  } else {
    showToast('删除失败');
  }
};

const toEditBlog = (id: number) => {
  router.push(`/blog/edit/${id}`);
};

const starBlog = async (id: number, isStarred: boolean) => {
  const res: any = await myAxios.post('/blog/star', {
    blogId: id,
    isStarred: isStarred
  });
  if (res?.code === 0) {
    showToast('点赞成功');
  } else {
    showToast('点赞失败');
  }
};

const likeBlog = async (id: number, isLiked: boolean) => {
  const res: any = await myAxios.post('/blog/like', {
    blogId: id,
    isLiked: isLiked
  });
  if (res?.code === 0) {
    showToast('点赞成功');
  } else {
    showToast('点赞失败');
  }
};

const toBlog = (id: number) => {
  console.log(id);
  router.push({
    path: `/blog/detail/${id}`
  });
};

// 安全获取博客标签
const getBlogTags = (blog: Blog) => {
  if (!blog || !blog.tags) {
    return [];
  }
  try {
    return JSON.parse(blog.tags);
  } catch (e) {
    console.error('解析博客标签出错:', e);
    return [];
  }
}

</script>

<style scoped>
.button {
  height: 100%;
}

</style>